package com.zkh.myframe.filter;

import java.io.IOException;
import java.nio.charset.Charset;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zkh.myframe.core.Chain;
import com.zkh.myframe.core.FrameConfigure;
import com.zkh.myframe.core.FrameUtils;
import com.zkh.myframe.exception.BaseException;
import com.zkh.myutils.code.Charsets;
import com.zkh.myutils.io.log.Logger;
import com.zkh.myutils.utils.StringUtils;

public class CoreFilter implements Filter {
	//编码
	private static Charset charset = Charsets.UTF_8;

	/**
	 * 核心过滤器
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
			throws IOException, ServletException {
		//获取request和response
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		//获取contextPath
		String cpath = req.getContextPath();
		//将项目名放入request域（404、500页面可能会用到ctx变量）
		req.setAttribute("ctx", cpath);
		//获取URI
		String uri = req.getRequestURI();
		//后缀
		String suffix = FrameUtils.getUrlSuffix(uri);
		/******** Controller映射设置  *********/
		String relate = uri.substring(cpath.length());
		//检查是否是首页访问，且有无首页拦截
		if("/".equals(relate) && !FrameConfigure.getFirstPage().isEmpty()){
			relate = FrameConfigure.getFirstPage();
		}
		//如果有后缀，则去掉后缀
		if(!suffix.isEmpty()) {
			relate = relate.substring(0, relate.length()-suffix.length()-1);
		}
		//保存处理后的URI
		request.setAttribute("URI", relate);
		//获取Controller
		Object[] controllerName = FrameConfigure.getControllerName(relate);
		//如果匹配到映射，则执行后续步骤
		if(controllerName!=null){
			/******* 过滤编码  ********/
			if(req.getMethod().equalsIgnoreCase("POST")){
				//如果是POST请求，可直接设置
				request.setCharacterEncoding(charset.name());
			}//如果是其它请求，调用GetRequest()方法
			else if(!(req instanceof GetRequest)){
				//暂时GET请求没有编码问题，默认UTF-8（此处为无效代码）
				req = new GetRequest(req, charset);
			}
			//释放请求
			try{
				//获取链对象
				Chain dchain = new Chain(request, response, controllerName);
				//执行下一条链
				dchain.nextChain();
			} catch(BaseException e){
				if(e.getErrorCode()==404){
					resp.sendError(404, "你请求的页面不存在");
				}else if(e.getErrorCode()==999) {
					//放行
					chain.doFilter(request, response);
				}else{
					//错误页面
					String excepPage = FrameConfigure.getBaseExceptionPage();
					//为空
					if(!StringUtils.isEmpty(excepPage)) {
						//错误信息
						request.setAttribute("e", e);
						//跳转到错误页面
						request.getRequestDispatcher(excepPage).forward(request, response);
					}else {
						Logger.error(e);
						resp.sendError(500);
					}
				}
			}catch(Exception e){
				Logger.error(e);
				resp.sendError(500);
			}
		}else{
			//放行
			chain.doFilter(request, response);
		}
	}

	public void destroy() {}
	public void init(FilterConfig config) throws ServletException {
		//如果未读取配置，则读取配置
		if(charset==null){
			//读取编码过滤器要转换的编码
			charset = FrameConfigure.getGlobalCharset();
		}
	}
	
}
